const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

// 数据库连接配置
const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'demo'
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 在 app.js 顶部添加数据库连接测试
async function testDatabaseConnection() {
    try {
        const connection = await mysql.createConnection(dbConfig);
        console.log('数据库连接成功');
        await connection.end();
    } catch (error) {
        console.error('数据库连接失败:', error);
        process.exit(1);
    }
}

// 验证 JWT token 的中间件
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
        return res.status(401).json({ message: '未提供认证token' });
    }

    jwt.verify(token, 'your_jwt_secret', (err, user) => {
        if (err) {
            return res.status(403).json({ message: 'token无效或已过期' });
        }
        req.user = user;
        next();
    });
};

// 登录接口
app.post('/api/login', async (req, res) => {
    console.log('收到登录请求:', req.body);
    const { username, password } = req.body;

    if (!username || !password) {
        console.log('用户名或密码为空');
        return res.status(400).json({
            message: '用户名和密码不能为空'
        });
    }

    try {
        // 从数据库查询用户
        const [rows] = await pool.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [username, password]
        );
        console.log('数据库查询结果:', rows);

        if (rows.length === 0) {
            console.log('用户名或密码错误');
            return res.status(401).json({
                message: '用户名或密码错误'
            });
        }

        const user = rows[0];
        console.log('登录成功:', user.username);

        // 生成 JWT token
        const token = jwt.sign(
            { userId: user.id, username: user.username },
            'your_jwt_secret',
            { expiresIn: '24h' }
        );

        // 返回成功响应
        res.json({
            message: '登录成功',
            token,
            user: {
                id: user.id,
                username: user.username,
                // 可以添加其他需要的用户信息
            }
        });

    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({
            message: '服务器错误，请稍后重试'
        });
    }
});

// 添加一个测试接口
app.get('/api/test', (req, res) => {
    res.json({ message: '服务器正常运行' });
});

// 获取游戏详情
app.get('/api/games/:id', async (req, res) => {
    try {
        const [rows] = await pool.execute(
            'SELECT * FROM games WHERE id = ?',
            [req.params.id]
        );

        if (rows.length === 0) {
            return res.status(404).json({ message: '游戏不存在' });
        }

        const game = rows[0];
        try {
            // 解析JSON字符串
            game.genres = typeof game.genres === 'string' ? JSON.parse(game.genres) : [];
            game.tags = typeof game.tags === 'string' ? JSON.parse(game.tags) : [];
        } catch (parseError) {
            console.error('JSON解析错误:', parseError, '游戏数据:', game);
            game.genres = [];
            game.tags = [];
        }

        res.json(game);
    } catch (error) {
        console.error('获取游戏详情失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取游戏评论列表
app.get('/api/games/:id/reviews', async (req, res) => {
    try {
        const [rows] = await pool.execute(
            `SELECT r.*, u.username 
             FROM reviews r 
             JOIN users u ON r.user_id = u.id 
             WHERE r.game_id = ? 
             ORDER BY r.created_at DESC`,
            [req.params.id]
        );

        res.json(rows);
    } catch (error) {
        console.error('获取评论失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 添加游戏评论
app.post('/api/games/:id/reviews', authenticateToken, async (req, res) => {
    const { content, rating } = req.body;
    const gameId = req.params.id;
    const userId = req.user.userId;

    // 验证评分范围
    if (rating < 1 || rating > 5) {
        return res.status(400).json({ message: '评分必须在1-5之间' });
    }

    try {
        // 检查游戏是否存在
        const [games] = await pool.execute(
            'SELECT id FROM games WHERE id = ?',
            [gameId]
        );

        if (games.length === 0) {
            return res.status(404).json({ message: '游戏不存在' });
        }

        // 检查用户是否已经评论过
        const [existingReviews] = await pool.execute(
            'SELECT id FROM reviews WHERE game_id = ? AND user_id = ?',
            [gameId, userId]
        );

        if (existingReviews.length > 0) {
            return res.status(400).json({ message: '您已经评论过这款游戏' });
        }

        // 添加评论
        await pool.execute(
            'INSERT INTO reviews (game_id, user_id, content, rating) VALUES (?, ?, ?, ?)',
            [gameId, userId, content, rating]
        );

        // 更新游戏的平均评分
        await pool.execute(
            `UPDATE games 
             SET rating = (
                 SELECT AVG(rating) 
                 FROM reviews 
                 WHERE game_id = ?
             )
             WHERE id = ?`,
            [gameId, gameId]
        );

        res.json({ message: '评论添加成功' });
    } catch (error) {
        console.error('添加评论失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取所有游戏列表
app.get('/api/games', async (req, res) => {
    try {
        const [rows] = await pool.execute('SELECT * FROM games');
        // 解析每个游戏的JSON字段，添加错误处理
        const games = rows.map(game => {
            try {
                return {
                    ...game,
                    genres: typeof game.genres === 'string' ? JSON.parse(game.genres) : [],
                    tags: typeof game.tags === 'string' ? JSON.parse(game.tags) : []
                };
            } catch (parseError) {
                console.error('JSON解析错误:', parseError, '游戏数据:', game);
                return {
                    ...game,
                    genres: [],
                    tags: []
                };
            }
        });
        res.json(games);
    } catch (error) {
        console.error('获取游戏列表失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 在启动服务器之前测试数据库连接
testDatabaseConnection().then(() => {
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
        console.log(`服务器运行在端口 ${PORT}`);
    });
}); 